<template>
  <div class="user-list-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-container">
        <el-form :model="searchForm" inline>
          <el-form-item label="商户">
            <el-select
              v-model="searchForm.MerchantId"
              placeholder="请选择商户"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="item in merchantIdOptions"
                :key="item.Id"
                :label="item.Name"
                :value="item.Id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- Banking AV账户信息表格 -->
      <el-table 
        :data="list" 
        v-loading="loading"
        style="width: 100%"
        :default-sort="{ prop: 'createdAt', order: 'descending' }"
        empty-text="暂无数据"
      >
        <el-table-column prop="Id" label="ID" width="80" />
        <el-table-column prop="MerchantId" label="商户ID" width="100" />
        <el-table-column prop="Merchant" label="商户名称" width="120">
          <template #default="scope">
            <span>{{ scope.row.Merchant?.Name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="AccountHolder" label="账户持有人" width="150" show-overflow-tooltip />
        <el-table-column prop="CompanyName" label="公司名称" width="150" show-overflow-tooltip />
        <el-table-column prop="Iban" label="银行账号" width="200" show-overflow-tooltip>
          <template #default="scope">
            <div class="copy-cell">
              <span class="text-ellipsis">{{ scope.row.Iban }}</span>
              <el-button 
                type="text" 
                size="small" 
                @click="handleCopy(scope.row.Iban, '银行账号')"
                class="copy-btn"
                v-if="scope.row.Iban"
              >
                <el-icon><DocumentCopy /></el-icon>
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="swiftCode" label="SWIFT代码" width="150" show-overflow-tooltip>
          <template #default="scope">
            <div class="copy-cell">
              <span class="text-ellipsis">{{ scope.row.SwiftCode }}</span>
              <el-button 
                type="text" 
                size="small" 
                @click="handleCopy(scope.row.SwiftCode, 'SWIFT代码')"
                class="copy-btn"
                v-if="scope.row.SwiftCode"
              >
                <el-icon><DocumentCopy /></el-icon>
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="BankName" label="银行名称" width="150" show-overflow-tooltip />
        <el-table-column prop="BankAddress" label="银行地址" width="200" show-overflow-tooltip />
        <el-table-column prop="BankCountryCode" label="银行国家代码" width="120" />
        <el-table-column prop="PayoutReference" label="支付参考" width="150" show-overflow-tooltip />
        <el-table-column prop="AddressStreetAddress" label="街道地址" width="200" show-overflow-tooltip />
        <el-table-column prop="AddressCity" label="城市" width="120" />
        <el-table-column prop="AddressState" label="州/省" width="120" />
        <el-table-column prop="AddressPostalCode" label="邮编" width="120" />
        <el-table-column prop="AddressCountry" label="国家" width="100" />
        <el-table-column prop="UpdatedAtString" label="修改时间" width="180" show-overflow-tooltip />
        <el-table-column prop="CreatedAtString" label="创建时间" width="180" show-overflow-tooltip />
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="scope">
            <el-button type="text" size="small" @click="handleEdit(scope.row)">更新</el-button>         
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/更新Banking AV账户信息对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :before-close="handleClose"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="150px"
      >
        <el-form-item label="商户" prop="MerchantId" v-if="dialogType === 'add'">
          <el-select
            v-model="userForm.MerchantId"
            placeholder="请选择商户"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in merchantIdOptions"
              :key="item.Id"
              :label="item.Name"
              :value="item.Id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="账户持有人" prop="AccountHolder">
          <el-input v-model="userForm.AccountHolder" placeholder="请输入账户持有人" />
        </el-form-item>
        <el-form-item label="公司名称" prop="CompanyName">
          <el-input v-model="userForm.CompanyName" placeholder="请输入公司名称" />
        </el-form-item>
        <el-form-item label="银行账号" prop="Iban">
          <el-input v-model="userForm.Iban" placeholder="请输入银行账号" />
        </el-form-item>
        <el-form-item label="SWIFT代码" prop="SwiftCode">
          <el-input v-model="userForm.SwiftCode" placeholder="请输入SWIFT代码" />
        </el-form-item>
        <el-form-item label="银行名称" prop="BankName">
          <el-input v-model="userForm.BankName" placeholder="请输入银行名称" />
        </el-form-item>
        <el-form-item label="银行地址" prop="BankAddress">
          <el-input v-model="userForm.BankAddress" placeholder="请输入银行地址" />
        </el-form-item>
        <el-form-item label="银行国家代码" prop="BankCountryCode">
          <el-input v-model="userForm.BankCountryCode" placeholder="请输入银行国家代码" />
        </el-form-item>
        <el-form-item label="支付参考" prop="PayoutReference">
          <el-input v-model="userForm.PayoutReference" placeholder="请输入支付参考" />
        </el-form-item>
        <el-form-item label="地址街道" prop="AddressStreetAddress">
          <el-input v-model="userForm.AddressStreetAddress" placeholder="请输入地址街道" />
        </el-form-item>
        <el-form-item label="地址城市" prop="AddressCity">
          <el-input v-model="userForm.AddressCity" placeholder="请输入地址城市" />
        </el-form-item>
        <el-form-item label="地址州/省" prop="AddressState">
          <el-input v-model="userForm.AddressState" placeholder="请输入地址州/省" />
        </el-form-item>
        <el-form-item label="地址邮编" prop="AddressPostalCode">
          <el-input v-model="userForm.AddressPostalCode" placeholder="请输入地址邮编" />
        </el-form-item>
        <el-form-item label="地址国家" prop="AddressCountry">
          <el-input v-model="userForm.AddressCountry" placeholder="请输入地址国家" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { DocumentCopy } from '@element-plus/icons-vue'
import { bankingAvInfoList, createBankingAvInfo, updateBankingAvInfo } from '@/api/merchant'
import { merchantList } from '@/api/selectList'

// 响应式数据
const loading = ref(false)
const list = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' or 'edit'
const userFormRef = ref()
const merchantIdOptions = ref([])

// 搜索表单
const searchForm = reactive({
  MerchantId: null
})

// Banking AV账户信息表单
const userForm = reactive({
  Id: 0,
  MerchantId: null,
  AccountHolder: '',
  AddressCity: '',
  AddressCountry: '',
  AddressPostalCode: '',
  AddressState: '',
  AddressStreetAddress: '',
  BankAddress: '',
  BankCountryCode: '',
  BankName: '',
  CompanyName: '',
  Iban: '',
  PayoutReference: '',
  SwiftCode: ''
})

// 表单验证规则（所有字段都是必填）
const userRules = {
  MerchantId: [
    { required: true, message: '请选择商户', trigger: 'change' }
  ],
  AccountHolder: [
    { required: true, message: '请输入账户持有人', trigger: 'blur' }
  ],
  CompanyName: [
    { required: true, message: '请输入公司名称', trigger: 'blur' }
  ],
  Iban: [
    { required: true, message: '请输入银行账号', trigger: 'blur' }
  ],
  SwiftCode: [
    { required: true, message: '请输入SWIFT代码', trigger: 'blur' }
  ],
  BankName: [
    { required: true, message: '请输入银行名称', trigger: 'blur' }
  ],
  BankAddress: [
    { required: true, message: '请输入银行地址', trigger: 'blur' }
  ],
  BankCountryCode: [
    { required: true, message: '请输入银行国家代码', trigger: 'blur' }
  ],
  PayoutReference: [
    { required: true, message: '请输入支付参考', trigger: 'blur' }
  ],
  AddressStreetAddress: [
    { required: true, message: '请输入地址街道', trigger: 'blur' }
  ],
  AddressCity: [
    { required: true, message: '请输入地址城市', trigger: 'blur' }
  ],
  AddressState: [
    { required: true, message: '请输入地址州/省', trigger: 'blur' }
  ],
  AddressPostalCode: [
    { required: true, message: '请输入地址邮编', trigger: 'blur' }
  ],
  AddressCountry: [
    { required: true, message: '请输入地址国家', trigger: 'blur' }
  ]
}

// 计算属性
const dialogTitle = computed(() => {
  return dialogType.value === 'add' ? '新增Banking AV账户信息' : '更新Banking AV账户信息'
})

// 获取商户列表
const getList = async () => {
  loading.value = true
  try {
    const res = await bankingAvInfoList({
      Page: currentPage.value,
      PageSize: pageSize.value,
      ...searchForm
    })
    if (res.code === 200) {
      list.value = res.data?.List || []
      total.value = res.data?.Total
    } else {
      ElMessage.error('获取商户列表失败')
    }
  } catch (error) {
    ElMessage.error('获取商户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    MerchantId: null
  })
  currentPage.value = 1
  getList()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pageSize.value = size
  getList()
}

// 当前页改变
const handleCurrentChange = (page) => {
  currentPage.value = page
  getList()
}

// 新增Banking AV账户信息
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  resetForm()
}

// 编辑Banking AV账户信息
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  // 深拷贝数据，避免直接修改
  Object.assign(userForm, {
    Id: row.Id || null,
    AccountHolder: row.AccountHolder || '',
    AddressCity: row.AddressCity || '',
    AddressCountry: row.AddressCountry || '',
    AddressPostalCode: row.AddressPostalCode || '',
    AddressState: row.AddressState || '',
    AddressStreetAddress: row.AddressStreetAddress || '',
    BankAddress: row.BankAddress || '',
    BankCountryCode: row.BankCountryCode || '',
    BankName: row.BankName || '',
    CompanyName: row.CompanyName || '',
    Iban: row.Iban || '',
    PayoutReference: row.PayoutReference || '',
    SwiftCode: row.SwiftCode || '',
    MerchantId: row.Merchant?.Id || null
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!userFormRef.value) return
  
  try {
    await userFormRef.value.validate()
    const submitData = {
      AccountHolder: userForm.AccountHolder,
      AddressCity: userForm.AddressCity,
      AddressCountry: userForm.AddressCountry,
      AddressPostalCode: userForm.AddressPostalCode,
      AddressState: userForm.AddressState,
      AddressStreetAddress: userForm.AddressStreetAddress,
      BankAddress: userForm.BankAddress,
      BankCountryCode: userForm.BankCountryCode,
      BankName: userForm.BankName,
      CompanyName: userForm.CompanyName,
      Iban: userForm.Iban,
      PayoutReference: userForm.PayoutReference,
      SwiftCode: userForm.SwiftCode
    }
    
    if (dialogType.value === 'add') {
      // 新增Banking AV账户信息
      submitData.Id = null
      submitData.MerchantId = userForm.MerchantId
      const res = await createBankingAvInfo(submitData)
      if (res.code === 200) {
        ElMessage.success('新增Banking AV账户信息成功')
        dialogVisible.value = false
        getList()
      } else {
        ElMessage.error(res.message || '新增失败')
      }
    } else {
      // 更新Banking AV账户信息
      submitData.Id = userForm.Id
      const res = await updateBankingAvInfo(submitData)
      if (res.code === 200) {
        ElMessage.success('更新Banking AV账户信息成功')
        dialogVisible.value = false
        getList()
      } else {
        ElMessage.error(res.message || '更新失败')
      }
    }
  } catch (error) {
    console.error(error)
  }
}

// 重置表单
const resetForm = () => {
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
  Object.assign(userForm, {
    Id: 0,
    MerchantId: null,
    AccountHolder: '',
    AddressCity: '',
    AddressCountry: '',
    AddressPostalCode: '',
    AddressState: '',
    AddressStreetAddress: '',
    BankAddress: '',
    BankCountryCode: '',
    BankName: '',
    CompanyName: '',
    Iban: '',
    PayoutReference: '',
    SwiftCode: ''
  })
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}

const getMerchantIdOptions = async () => {
  try {
    const res = await merchantList()
    if (res.code === 200) {
      merchantIdOptions.value = res.data || []
    }
  } catch (error) {
    console.error(error)
  }
}

// 生命周期
onMounted(() => {
  getList()
  getMerchantIdOptions()
})

// 复制功能
const handleCopy = async (text, fieldName) => {
  try {
    if (!text) {
      ElMessage.warning('复制内容为空')
      return
    }
    
    // 使用现代浏览器的 Clipboard API
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(text)
      ElMessage.success(`${fieldName}复制成功`)
    } else {
      // 降级方案：使用传统的 document.execCommand
      const textArea = document.createElement('textarea')
      textArea.value = text
      textArea.style.position = 'fixed'
      textArea.style.left = '-999999px'
      textArea.style.top = '-999999px'
      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()
      
      try {
        const successful = document.execCommand('copy')
        if (successful) {
          ElMessage.success(`${fieldName}复制成功`)
        } else {
          ElMessage.error('复制失败')
        }
      } catch (err) {
        ElMessage.error('复制失败')
      }
      
      document.body.removeChild(textArea)
    }
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败')
  }
}
</script>

<style scoped>
.user-list-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-table .cell) {
  white-space: nowrap;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 20px;
  margin-bottom: 10px;
}

:deep(.el-table__header-wrapper .cell) {
  white-space: normal;
  word-break: break-all;
  line-height: 1.5;
}

/* 复制按钮样式 */
.copy-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.text-ellipsis {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  min-width: 0;
}

.copy-btn {
  flex-shrink: 0;
  padding: 4px;
  margin: 0;
}

.copy-btn:hover {
  color: var(--el-color-primary);
}
:deep(.el-dialog) {
  max-height: 500px;
  overflow: auto;
}

/* 让表格滚动条始终显示 */
::v-deep(.el-table__body-wrapper .el-scrollbar__bar) {
  display: block!important;
}
:deep(.el-scrollbar__thumb) {
  background-color: #909399;
  opacity: 1;
}
</style>
